from app.db.session import SessionLocal
from app.models.generate import ServerList
from app.api.generate.schemas import server_list_schema as schema

from app.utils.curd_base import ModelCRUD
from app.utils import security
from app.utils.custom_response import success_response
from fastapi import APIRouter, Query, Body, Path, UploadFile, File, Form
from fastapi import Depends, Request
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.models.system import Users
from typing import Any, Dict, Union, List, Optional
from fastapi.encoders import jsonable_encoder
from app.utils.custom_exc import CustomException
from sqlalchemy import func, or_, not_
import uuid


class ServerListCRUD(ModelCRUD):
    model = ServerList


crud = ServerListCRUD()
router = APIRouter()


@router.post("/create_server", summary="新增服务", response_model=schema.Res, name='新增服务')
async def create_server(
    *,
    db: Session = Depends(get_db),
    req_data: schema.Req,
    current_user: Users = Depends(security.verify_admin_permission),
) -> Any:
    req_data = req_data.dict()

    req_data['uid'] = str(uuid.uuid4())
    # print(req_data)
    instance = crud.create(db, data=schema.Create.validate(req_data))
    only = ('id', 'name', 'state', 'uid', 'detail')
    return success_response(data=instance.to_dict(only=only))


@router.post("/delete_server", summary="删除服务", response_model=schema.Res, name='删除服务')
async def delete_server(
    *,
    db: Session = Depends(get_db),
    req_data: schema.Del,
    current_user: Users = Depends(security.verify_admin_permission),
) -> Any:

    crud.destroy(db, req_body=req_data)
    return success_response(data={})


@router.post("/update_server/{pk}", summary="更新服务", response_model=schema.Res, name='更新服务')
async def update_permission(
    *,
    db: Session = Depends(get_db),
    pk,
    permission_info: schema.Update,
    current_user: Users = Depends(security.verify_admin_permission),
) -> Any:

    instance = crud.get_object(db, pk)
    instance = crud.update(db, instance=instance, data=permission_info)
    only = ('id', 'name', 'state', 'uid', 'detail')
    return success_response(data=instance.to_dict(only=only))


able_filter_list = [
    {'name': 'name', 'source_filed': 'name', 'lookup_expr': 'ic', 'label': '包含名字', 'type': str, 'method': None, 'required': False},
]


@router.get("/get_server_list", summary="获取服务列表", response_model=schema.Res, name='获取服务列表')
async def get_server_list(
    request: Request,
    *,
    db: Session = Depends(get_db),
    page: int = Query(1, description='页码', ge=1),
    page_size: int = Query(10, description='页面大小', le=50, ge=1),
    name: str = Query(None, description='名字'),
    current_user: Users = Depends(security.verify_access_token),
) -> Any:
    order_by_fields = ('-id',)
    queryset, total = crud.get_page_queryset(db, page=page, page_size=page_size, req_data=request.query_params, able_filter_list=able_filter_list, order_by_fields=order_by_fields)
    only = ('id', 'name', 'state', 'uid', 'detail')
    items = crud.serializer(queryset, only=only)
    resp = {
        "items": items,
        'total': total
    }
    return success_response(data=resp)


def setup_set_server_state():
    db = SessionLocal()
    queryset = crud.queryset(db)
    queryset.update({ServerList.state: 1})
    db.commit()



